package org.zjvis.datascience.service.kg;


import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.*;


/**
 * @Description : 知识图谱相关service
 * @Date 2022-06-20
 */
@Service
public class KnowledgeGraphService {
    @Value("${restful.knowledgeGraph.url:#{null}}")
    private String KG_SERVICE_API;
    @Value("${restful.knowledgeGraphConstruct.url:#{null}}")
    private String KGConstruct_SERVICE_API;
    private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
        .callTimeout(60, TimeUnit.SECONDS)
        .readTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .build();

    public Response queryNebulaWithFile(String api, MultipartFile multipartFile, Map<String, String> params) {
        try {
            String requestParam = getRequestParam(params);
            String fileName = multipartFile.getOriginalFilename();
            String ext = fileName.substring(fileName.lastIndexOf("."));
            File file = File.createTempFile(fileName, ext);
            multipartFile.transferTo(file);
            RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("owlFile", fileName,
                    RequestBody.create(MediaType.parse(org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE), file))
                .build();

            Request request = new Request.Builder()
                .url(KG_SERVICE_API + api + requestParam)
                .post(requestBody)
                .build();

            Call call = OK_HTTP_CLIENT.newCall(request);
            return call.execute();
        } catch (IOException ioException) {
            throw new RuntimeException(ioException.getMessage());
        }

    }
    public Response queryNebulaFile(String api, MultipartFile multipartFile) {
        try {
            String fileName = multipartFile.getOriginalFilename();
            String ext = fileName.substring(fileName.lastIndexOf("."));
            File file = File.createTempFile(fileName, ext);
            multipartFile.transferTo(file);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("uploadFile", fileName,
                            RequestBody.create(MediaType.parse(org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE), file))
                    .build();

            Request request = new Request.Builder()
                    .url(KGConstruct_SERVICE_API + api )
                    .post(requestBody)
                    .build();

            Call call = OK_HTTP_CLIENT.newCall(request);
            return call.execute();
        } catch (IOException ioException) {
            throw new RuntimeException(ioException.getMessage());
        }

    }
    public Response queryNebula(Map<String, String> params, String api) {
        if (KG_SERVICE_API == null) {
            return null;
        }
        String requestParam = getRequestParam(params);
        Request request = new Request.Builder()
            .url(KG_SERVICE_API + api + requestParam)
            .post(
                RequestBody.create(MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE), "")
            )
            .build();

        Call call = OK_HTTP_CLIENT.newCall(request);
        try {
            return call.execute();
        } catch (IOException ioException) {
            throw new RuntimeException(ioException.getMessage());
        }
    }

    public Response queryNebulaByGet(Map<String, String> params, String api) throws IOException {
        String requestParam = getRequestParam(params);
        Request request = new Request.Builder()
            .url(KG_SERVICE_API + api + requestParam)
            .build();
        Call call = OK_HTTP_CLIENT.newCall(request);
        return call.execute();
    }

    public Response queryKGByGet(Map<String, String> params, String api) throws IOException {
        String requestParam = getRequestParam(params);
        Request request = new Request.Builder()
                .url(KGConstruct_SERVICE_API + api + requestParam)
                .build();
        Call call = OK_HTTP_CLIENT.newCall(request);
        return call.execute();
    }

    private String getRequestParam(Map<String, String> params) {
        String requestParam = "";
        if (!params.isEmpty()) {
            requestParam = "?";
            for (Map.Entry<String, String> entry : params.entrySet()) {
                requestParam = requestParam + entry.getKey() + "=" + entry.getValue() + "&&";
            }
            requestParam = requestParam.substring(0, requestParam.lastIndexOf("&&"));
        }
        return requestParam;
    }
}
